<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Socket.IO chat</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>
  <style>
    li{
      padding: 4px 10px;
      border: 1px solid #eee;
      width:fit-content;
      border-radius: 5px;
      margin-bottom: 10px;
    }
  </style>
  <body>
    <div class="container" style="margin-top:100px">
        <div class="panel panel-default">
            <div class="panel-heading">Socket.IO 简易聊天室</div>
            <div class="panel-body">
                <div class="col-md-12">
                    <ul class="messages pull-letf list-unstyled"></ul>
                    <form action="">
                      <div class="form-group">
                        <textarea class="form-control"  placeholder="输入发言内容"></textarea>
                      </div>
                      <button type="button" class="btn btn-primary">发言</button>
                    </form>
                </div>
            </div>
          </div>
    </div>
    
    
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
        $(function () {
            var socket = io();

            // 调用io()方法，生成socket对象，当点击按钮的时候，使用socket.emit发送事件
            $('.btn').click(function(){
              socket.emit('chat message', $('.form-control').val());
              $('.form-control').val('');
            });

            // 捕获 chat message事件 将返回的消息添加到页面中
            socket.on('chat message', function(msg){
              $('.messages').append($('<li>').text(msg));
            });  
        });
    </script>
  </body>
</html>